<template>
    <div>
        <el-row style="margin-top: 10px;" v-if="$store.state.userInfo.groups == 1">
            <el-col :span="8">
                <el-button type="primary" class="btn-size" @click="createdUser">创建用户</el-button>
                <el-button type="danger" class="btn-size" @click="RemoveUserAll">批量删除</el-button>
            </el-col>

            <el-col :span="16">
                <el-form :inline="true" class="demo-form-inline" :model="params">
                    <el-form-item label="用户">
                        <el-input v-model="params.username" placeholder="用户名" class="input-width"></el-input>
                    </el-form-item>
                    <el-form-item label="用户组">
                        <el-select v-model="params.group" placeholder="用户组">
                            <el-option
                                v-for="item in groups"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="onSubmit">查询</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
        <el-table
            ref="multipleTable"
            :data="user.data"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectionChange">
            <el-table-column
                type="selection"
                align="center"
                width="55">
            </el-table-column>
            <el-table-column
                prop="username"
                label="工号"
                align="center"
                width="150">
            </el-table-column>
            <el-table-column
                prop="first_name"
                label="姓名"
                align="center"
                width="150">
            </el-table-column>
            <el-table-column
                label="用户组"
                align="center"
                width="150"
            >
                <template slot-scope="scope">
                    <p v-if="scope.row.groups.length===0">无</p>
                    <p v-else>
                        <span v-for="group in scope.row.groups">
                            {{group.name}}<br/>
                    </span>
                    </p>
                </template>

            </el-table-column>
            <el-table-column
                label="用户状态"
                align="center"
                width="150">
                <template slot-scope="scope">{{ scope.row.is_active===1?'活跃':'非活跃' }}</template>
            </el-table-column>
            <el-table-column
                prop="created_at"
                label="创建时间"
                align="center"
                min-width="200">
            </el-table-column>
            <el-table-column
                fixed="right"
                label="操作"
                width="150"
                align="center">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        @click="handleEdit(scope.row)">编辑
                    </el-button>
                    <el-button
                        size="mini"
                        type="danger"
                        @click="handleDelete(scope.row)"
                        v-if="$store.state.userInfo.groups == 1">删除
                    </el-button>
                </template>

            </el-table-column>
        </el-table>
        <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :total="user.total"
            :page-size="params.page_size"
            :page-sizes="[8, 20, 30, 40, 100]"
            :current-page="params.page"
            layout="prev, pager, next, sizes"
            align="center">
        </el-pagination>
        <el-dialog :title="modalTitle" :visible.sync="dialogFormVisible">
            <el-form :model="userForm" ref="userForm">
                <el-form-item label="工号" prop="username" :label-width="formLabelWidth">
                    <el-input v-model="userForm.username" autocomplete="off"></el-input>
                </el-form-item>

                <el-form-item label="密码" prop="password" :label-width="formLabelWidth">
                    <el-input v-model="userForm.password" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="c_password" :label-width="formLabelWidth">
                    <el-input v-model="userForm.c_password" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitAddUser">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog :title="modalTitle" :visible.sync="dialogFormEdit">
            <el-form :model="editUserForm" ref="editUserForm">
                <el-form-item label="账户信息" :label-width="formLabelWidth" style="background-color:#4882FF;">
                </el-form-item>
                <el-form-item label="工号" prop="username" :label-width="formLabelWidth">
                    <el-input v-model="editUserForm.username" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="姓名" prop="first_name" :label-width="formLabelWidth">
                    <el-input v-model="editUserForm.first_name" autocomplete="off"></el-input>
                </el-form-item>
                <div v-if="$store.state.userInfo.groups == 1">
                    <el-form-item label="权限" :label-width="formLabelWidth" style="background-color:#4882FF;">
                    </el-form-item>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="管理员" :label-width="formLabelWidth">
                                <el-switch v-model="editUserForm.is_superuser" :active-value="1"
                                           :inactive-value="0"></el-switch>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="职员" :label-width="formLabelWidth">
                                <el-switch v-model="editUserForm.is_staff" :active-value="1"
                                           :inactive-value="0"></el-switch>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="用户状态" :label-width="formLabelWidth">
                                <el-switch v-model="editUserForm.is_active" :active-value="1"
                                           :inactive-value="0"></el-switch>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-form-item label="组" prop="groups" :label-width="formLabelWidth">
                        <el-transfer
                            filterable
                            :filter-method="filterMethod"
                            filter-placeholder="请输入组名"
                            :titles="['可用组', '选中的组']"
                            v-model="editUserForm.groups"
                            :props="{
                                key: 'id',
                                label: 'name'
                                }"
                            :data="groups">
                        </el-transfer>
                    </el-form-item>
                    <!--<el-form-item label="用户权限" :label-width="formLabelWidth">
                        <el-transfer
                            filterable
                            :filter-method="filterMethod"
                            filter-placeholder="请输入用户权限"
                            :titles="['可用用户权限', '选中的用户权限']"
                            v-model="value2"
                            :data="data2">
                        </el-transfer>
                    </el-form-item>-->

                </div>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormEdit = false">取 消</el-button>
                <el-button type="primary" @click="submitEditUser">保 存</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {
        updateUser,
        showUser,
        getUser,
        addUser,
        RemoveUser,
        getGroup
    } from "../../../api/api";

    export default {
        name: "addUser",
        data() {
            return {
                value2: [],
                filterMethod(query, item) {
                    return item.name.indexOf(query) > -1;
                },
                userForm: {
                    id: null,
                    username: null,
                    password: null,
                    c_password: null
                },
                editUserForm: {
                    id: null,
                    username: null,
                    first_name: null,
                    is_superuser: null,
                    is_staff: null,
                    is_active: null,
                    groups: []
                },
                groups: [],
                params: {
                    page: 1,
                    page_size: 8,
                    username: '',
                    group: ''
                },
                modalTitle: "",
                formLabelWidth: '120px',
                user: [],
                skip_page: "",
                multipleSelection: [],
                dialogFormVisible: false,
                dialogFormEdit: false,
                multipleTable: []
            }
        },
        created() {
            this.listUser(this.params);
            this.listGroup();
        },
        methods: {
            onSubmit: function () {
                this.listUser(this.params);
            },
            handleEdit: function (row) {
                this.modalTitle = "用户信息";
                this.$nextTick(() => {
                    this.$refs['editUserForm'].resetFields();
                });
                this.dialogFormEdit = true;
                showUser(row.id).then((response) => {
                    this.editUserForm.id = response.data.id;
                    this.editUserForm.username = response.data.username;
                    this.editUserForm.first_name = response.data.first_name;
                    this.editUserForm.is_superuser = response.data.is_superuser;
                    this.editUserForm.is_staff = response.data.is_staff;
                    this.editUserForm.is_active = response.data.is_active;
                    let groups = response.data.groups;
                    groups.forEach(group => {
                        this.editUserForm.groups.push(group.id);
                    });
                    //this.editUserForm.groups = response.data.groups;
                }).catch(function (error) {
                    console.log(error);
                });
            },
            handleDelete: function (row) {
                let _this = this;
                this.$confirm(`是否删除用户"${row.username}"?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    RemoveUser(row.id).then(() => {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.listUser(this.params);
                    }).catch(function (error) {
                        _this.$message({
                            type: 'error',
                            message: error.detail
                        });
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            listUser: function (params) {
                getUser(params).then((response) => {
                    this.user = response.data;
                    if (params.page>1 && this.user.data.length == 0) {
                        params.page = params.page -1;
                        this.listUser(params);
                    }
                }).catch(function (error) {
                    console.log(error);
                });
            },
            listGroup: function () {
                getGroup().then((response) => {
                    this.groups = response.data;
                }).catch(function (error) {
                    console.log(error);
                });
            },
            createdUser: function () {
                this.modalTitle = "添加用户";
                this.$nextTick(() => {
                    this.$refs['userForm'].resetFields();
                });
                this.dialogFormVisible = true;
                /*if (this.$refs['form']) {
                    this.$refs['form'].resetFields();
                }*/

            },
            submitAddUser: function () {
                this.dialogFormVisible = false;
                addUser(this.userForm).then(() => {
                    this.$message({
                        message: '恭喜你，创建成功',
                        type: 'success'
                    });
                    this.listUser(this.params);
                }).catch(function (error) {
                    console.log(error);
                });
            },
            submitEditUser: function () {
                this.dialogFormEdit = false;
                updateUser(this.editUserForm).then(() => {
                    this.$message({
                        message: '恭喜你，更新成功',
                        type: 'success'
                    });
                    this.listUser(this.params);
                }).catch(function (error) {
                    console.log(error);
                });
            },
            RemoveUserAll: function () {
                let _this = this;
                if (this.multipleSelection) {
                    let rows = this.multipleSelection;
                    let rowName = '';
                    rows.forEach((row, index, array) => {
                        if (index === array.length - 1) {
                            rowName += row.username;
                        } else {
                            rowName += row.username + ',';
                        }

                    });
                    this.$confirm(`是否删除用户"${rowName}"?`, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        rows.forEach((row, index, array) => {
                            if (index === array.length - 1) {
                                RemoveUser(row.id).then(res => {
                                    this.listUser(this.params);
                                    this.$message({
                                        type: 'success',
                                        message: '删除成功'
                                    });
                                }).catch(err => {
                                    this.listUser(this.params);
                                    console.log(err);
                                    _this.$message({
                                        type: 'error',
                                        message: '删除失败'
                                    });
                                });
                            } else {
                                RemoveUser(row.id).then(res => {

                                }).catch(err => {
                                    this.listUser(this.params);
                                    console.log(err);
                                    _this.$message({
                                        type: 'error',
                                        message: '删除失败'
                                    });
                                });
                            }
                        });
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        });
                    });

                }
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            handleSizeChange(val) {
                this.params.page_size = val;
                this.listUser(this.params);
            },
            handleCurrentChange(val) {
                this.params.page = val;
                this.listUser(this.params);
            }

        }
    }
</script>

<style>
    th {
        background: #F5F5F5;
        border-top: 1px solid #e6e6e6;
        border-bottom: 1px solid #e6e6e6;
    }

    tr {
        border-bottom: 1px solid #e6e6e6;
    }

    .demo-form-inline .input-width input {
        width: 320px !important;
    }

</style>
